import CryptoJS from "crypto-js";

let key = 'tongjiwisdom_key'; //与后台一样 16位 密码
let iv = CryptoJS.enc.Latin1.parse(key); //与后台一样   16位

let tools = {
	encryption(params) {
		let {
			data,
			type,
			param,
			key
		} = params;
		const result = JSON.parse(JSON.stringify(data));
		if (type === "Base64") {
			param.forEach(ele => {
				result[ele] = btoa(result[ele]);
			});
		} else {
			param.forEach(ele => {
				var data = result[ele];
				key = CryptoJS.enc.Latin1.parse(key);
				var iv = key;
				// 加密
				var encrypted = CryptoJS.AES.encrypt(data, key, {
					iv: iv,
					mode: CryptoJS.mode.CFB,
					padding: CryptoJS.pad.NoPadding
				});
				result[ele] = encrypted.toString();
			});
		}
		return result;
	},
	/*aes加密*/
	setAES(str) {
		let key = CryptoJS.enc.Utf8.parse(key); // 秘钥
		let iv = CryptoJS.enc.Utf8.parse(iv); //向量iv
		let encrypted = CryptoJS.AES.encrypt(str, key, {
			iv: iv,
			mode: CryptoJS.mode.CFB,
			padding: CryptoJS.pad.NoPadding
		});
		return encrypted.toString();
	},
	/*aes解密*/
	decryptAES(str) {
		let key = CryptoJS.enc.Utf8.parse(key); // 秘钥
		let iv = CryptoJS.enc.Utf8.parse(iv); //向量iv
		let decryptedData = CryptoJS.AES.decrypt(str, key, {
			iv: iv,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
		var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8);
		return decryptedStr;
	}
};

export default tools;
